package com.zhaokuner.parentstarter.handler;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * <p>
 * Description:保持请求中的关键数据用于转发，如会话，语言
 * <p>
 * Copyright: 天津联想协同科技有限公司
 * <p>
 *
 * @author 赵希坤 zhaoxikun
 * @date 2021/2/13 18:06
 */
@Component
public class HttpReqInfoUtil extends HttpReqInfo {

    public static String appServiceId;

    public static String appServiceVersion;

    @Value("${spring.application.name}")
    public void setAppServiceId(String serviceId) {
        HttpReqInfoUtil.appServiceId = serviceId;
    }

    @Value("${spring.application.version}")
    public void setAppServiceVersion(String serviceVersion) {
        HttpReqInfoUtil.appServiceVersion = serviceVersion;
    }

    /**
     * 服务ID
     */
    public static final String SERVICE_ID = "SERVICE_ID";
    /**
     * 服务版本
     */
    public static final String SERVICE_VERSION = "SERVICE_VERSION";
    /**
     * 会话id
     */
    public static final String LENOVO_SESSION_ID = "X-LENOVO-SESS-ID";
    /**
     * 语言
     */
    public static final String LANGUAGE = "language";

    /**
     * 初始化次数
     */
    private AtomicInteger initCount = new AtomicInteger(0);

    /**
     * 缓存
     */
    private static ThreadLocal<HttpReqInfoUtil> cache = ThreadLocal.withInitial(HttpReqInfoUtil::new);

    public static void initialize(HttpServletRequest request, HttpServletResponse response) {
        cache.get().initCount.incrementAndGet();
        cache.get().init(request, response);
    }

    /**
     * 方法描述：请求结束后清理本次请求的数据
     *
     * @author 赵希坤
     * @date 日期：2021/2/13 时间：18:17
     */
    public static void remove() {
        if (0 == cache.get().initCount.decrementAndGet()) {
            cache.remove();
        }
    }

    /**
     * 方法描述：数据
     *
     * @return java.lang.String
     * @author 赵希坤
     * @date 日期：2021/2/14 时间：20:10
     */
    public static HttpReqInfo get() {
        return cache.get();
    }


}
